# encoding: UTF-8

import string
import time

import douban.service
import douban.client
import urllib
import atom
import douban

import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


#这里的APIK_EY和SECRET可向豆瓣申请
API_KEY='0191d392751d3a6804b57ab75f******'
SECRET='6a9ecda6beec8***'
USER_ID = '25316233' #此处换成你的用户ID
#USER_ID = 'doubanclock'

request_tokens= {}

class AccessData(db.Model):
    user_id = db.StringProperty(required=True)
    request_key = db.StringProperty()
    request_secret = db.StringProperty()
    access_key = db.StringProperty()
    access_secret = db.StringProperty()

class MainPage(webapp.RequestHandler):
    def get(self):
        isAuth = False
        q = db.GqlQuery(" SELECT * FROM AccessData WHERE user_id = :1 ", USER_ID)
        x = q.count()
        if x and q[0].access_key and q[0].access_secret:
            isAuth = True
        template_values = {
            'isAuth': isAuth,
            }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))
        

class AuthPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.client = douban.client.OAuthClient(key=API_KEY, secret=SECRET)
        q = db.GqlQuery(" SELECT * FROM AccessData WHERE user_id = :1 ", USER_ID)
        x = q.count()
        if x:
            ad = q[0]
        else:
            ad = AccessData(user_id=USER_ID)

        global request_tokens
        if not ad.access_key and not ad.access_secret:
            ad.request_key = self.request.get('oauth_token','')
            ad.request_secret = request_tokens.get(ad.request_key)
            if ad.request_key and ad.request_secret:
                try:
                    a_key, a_secret, user_id = self.client.get_access_token(ad.request_key, ad.request_secret)
                    if user_id and a_key and a_secret:
                        if user_id != USER_ID:
                            self.response.out.write('授权失败，你不是目标用户')
                        else:
                            ad.access_key = a_key
                            ad.access_secret = a_secret
                            ad.put()
                            qq = db.GqlQuery(" SELECT * FROM AccessData WHERE user_id = :1 ", USER_ID)
                            self.response.out.write('获取用户授权成功，用户数：')
                            self.response.out.write(qq.count())
                    else:
                        self.response.out.write('获取用户授权失败,key,secret,user_id为空')
                except Exception:
                    ad.access_key = None
                    ad.access_secret = None
                    self.response.out.write('获取用户授权失败')
            else:
                key, secret = self.client.get_request_token()
                if key and secret:
                    request_tokens[key] = secret
                    ad.request_key = key
                    ad.request_secret = secret
                    url = self.client.get_authorization_url(key, secret, callback = self.request.url)
                    self.redirect(url)
                else:
                    self.response.out.write('获取 Request Token 失败')
                    
        else:
            self.response.out.write('该用户已经授权!')
            self.response.out.write('http://www.douban.com/people/'+ USER_ID + '/')    
        

class SendMessage(webapp.RequestHandler):
    def get(self):
        self.service = douban.service.DoubanService(api_key=API_KEY, secret=SECRET)
        q = db.GqlQuery(" SELECT * FROM AccessData WHERE user_id = :1 ", USER_ID)
        x = q.count()
        if x and q[0].access_key and q[0].access_secret:
            if self.service.ProgrammaticLogin(q[0].access_key, q[0].access_secret):
                now = time.localtime(time.time() + 1800)
                hour = time.strftime('%H', now)
                h = string.atoi(hour)
                h = h + 8
                if h >= 24:
                    h = h - 24
                noon1 = '上午'
                noon2 = '点整'
                if h > 12:
                    h = h - 12
                    noon1 = '下午'
                elif h == 0:
                    h = 12
                what_times = make_repeater(h)
                #result = what_times('咚！') + '（' + noon1 + str(h) + noon2 + '）'
                result = what_times('咚！')
                entry = douban.BroadcastingEntry()
                entry.content = atom.Content(text = result)
                entry = self.service.AddBroadcasting("/miniblog/saying", entry)
                self.response.out.write('send success')
            else:
                self.response.out.write('Service获取授权失败')
        else:
            self.response.out.write('获取用户授权失败,access_key,access_secret为空!')


application = webapp.WSGIApplication([('/', MainPage),('/auth', AuthPage), ('/message', SendMessage)], debug=True)

def make_repeater(n):
    return lambda s : s*n

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
